C语言线性链表的结点移动 您所在的位置:网站首页 c语言 移动文件指针 C语言线性链表的结点移动

C语言线性链表的结点移动

2023-03-26 05:30| 来源: 网络整理| 查看: 265

【问题描述】已知非空线性链表第1个链结点指针为list,链结点构造为

struct node{ datatype data; node *link; };

请写一算法,将该链表中数据域值最大的那个点移到链表的最后面。(假设链表中数据域值最大的链结点惟一)(注意:要求先写出算法的解题思路,然后再写出算法)【输入形式】输入为一个整数序列,整数之间以空格隔开,序列以回车结尾。【输出形式】输出为移动后的整数序列,整数之间以空格隔开,序列以回车结尾。【样例输入】3 12 4 9 5 1【样例输出】3 4 9 5 1 12【样例说明】将序列中最大的数字12移动到序列最后。

我的思路:1.先遍历链表找出那个最大值2.尾插最大值3.删最大值对应结点代码如下:

#define _CRT_SECURE_NO_WARNINGS 1 #include #include #include typedef int datatype; typedef struct node { datatype data; struct node* link; }node; node* BuySLTNode(datatype x) { node* newnode = (node*)malloc(sizeof(node)); if (newnode == NULL) { perror("malloc fail"); exit(-1); } newnode->data = x; newnode->link = NULL; return newnode; } node* CreateSList() { datatype data; node* phead = NULL, *ptail = NULL; while(1) { scanf("%d", &data); if (getchar() == '\n') { break; } node* newnode = BuySLTNode(data); if (phead == NULL) { ptail = phead = newnode; } else { ptail->link = newnode; ptail = newnode; } } return phead; } node* Find_max(node* phead) { node* cur = phead; node* Max = phead; datatype max = cur->data; while (cur) { if (cur->data > max) { max = cur->data; Max = cur; } cur = cur->link; } return Max; } void SListErase(node** pphead, node* pos) { assert(pos); assert(*pphead); if (pos == *pphead) { node* next = (*pphead)->link; free(*pphead); *pphead = next; } else { node* prev = *pphead; while (prev->link != pos) { prev = prev->link; } prev->link = pos->link; free(pos); } } void SLTPushBack(node** pphead, datatype x) { node* newnode = BuySLTNode(x); if (*pphead == NULL) { *pphead = newnode; } else { node* tail = *pphead; //找尾 while (tail->link) { tail = tail->link; } tail->link = newnode; } } void SLTPrint(node* phead) { node* cur = phead; while (cur) { printf("%d", cur->data); cur = cur->link; } } int main() { node* plist = (node*)malloc(sizeof(node)); plist = CreateSList(); node* max = Find_max(plist); SLTPushBack(plist, max->data); SListErase(plist, max); SLTPrint(plist); return 0; }

但是打印结果如下:

img

试图调试的时候发现:

img

不知道是哪里出错了 希望得到帮助 非常感谢



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有